package org.alex.samples.dao;

import java.util.List;

import org.alex.samples.model.ExamUserSubject;
import org.alex.samples.model.Subject;
import org.hibernate.type.IntegerType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
@Transactional
public class SubjectDAOImpl extends BaseHibernateDAO<Subject> implements ISubjectDAO {
	
	
	@Autowired
	IUserDAO userDAO;
	
	@Autowired
	ISubjectDAO subjectDAO;
	
	@Autowired
	IExamUserSubjectDAO usersubjectDAO;

	@Override
	public List<Subject> findAllSubject() {
		String hql = " FROM Subject ";
		List<Subject> subjectList = this.queryForList(hql, null);
		return subjectList;
	}

	@Override
	public void createSubject(Subject subject) {
		this.save(subject);
	}

	@Override
	public void deleteSubject(int id) {
		Subject subject = FindSubjectById(id);
		if(subject != null){
			this.delete(subject);
		}
	}

	@Override
	public Subject FindSubjectById(int id) {
		return this.get(id);
	}

	@Override
	public void editSubject(Subject subject) {
		this.update(subject);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Integer> findAllUserBySubject(Integer id) {
		StringBuilder sql = new StringBuilder();
		sql.append(" select user.user_id as userId ");
		sql.append(" from exam_user_subject eus ");
		sql.append(" left  join exam_subject es on eus.sub_id = es.sub_id ");
		sql.append(" left join exam_user user on user.user_id = eus.user_id ");
		sql.append(" where es.sub_id = :subjectId ");
		return this.createSqlQuery(String.valueOf(sql))
				.addScalar("userId",IntegerType.INSTANCE)
				.setInteger("subjectId", id)
				.list();
	}

	@Override
	public void inserSubjectUsers(List<Integer> insertList, Integer subjectId) {
		for(Integer i:insertList){
			ExamUserSubject examUserSubject = new ExamUserSubject();
			examUserSubject.setSubject(subjectDAO.get(subjectId));
			examUserSubject.setUser(userDAO.get(i));
			usersubjectDAO.save(examUserSubject);
		}
	}

	@Override
	public void deleteSubjectUsers(List<Integer> delList, Integer subjectId) {
		for(Integer i :delList){
			ExamUserSubject examUserSubject = new ExamUserSubject();
			examUserSubject.setSubject(subjectDAO.get(subjectId));
			examUserSubject.setUser(userDAO.get(i));
			usersubjectDAO.delete(examUserSubject);
		}
	}

}
